﻿using RulesEngine.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.ValidateRules.Lib
{
    /// <summary>
    /// 必填项，规则引擎基础验证属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class ValidateRulesRequiredAttribute : ValidateRulesBaseAttribute
    {
        /// <summary>
        /// 默认构造
        /// </summary>
        public ValidateRulesRequiredAttribute() : base()
        {
        }

        /// <summary>
        /// 获取或设置一个标志，该标志指示属性是否应允许空字符串。
        /// </summary>
        public bool AllowEmptyStrings { get; set; }

        /// <summary>
        /// 重写 <see cref="ValidationAttribute.IsValid(object)"/>
        /// </summary>
        /// <param name="value">要测试的值</param>
        /// <returns>
        ///     <c>false</c> 
        ///     如果 <paramref name="value" /> 为null或空字符串. 
        ///     如果 <see cref="RequiredAttribute.AllowEmptyStrings" /> 为 <c>false</c> 只验证 <paramref name="value" /> 为 null.
        /// </returns>
        public override bool IsValid(object? value)
        {
            if (value == null)
            {
                return false;
            }

            // only check string length if empty strings are not allowed
            return AllowEmptyStrings || !(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue);
        }
    }
}
